import { CommonModal } from "@/ui/modals/CommonModal/CommonModal";
import React, { useState } from "react";
import { RangeTimePicker } from "@/ui/RangeTimePicker/RangeTimePicker";
import cls from "@/styles/feature/CreateUserForm.module.scss";
import { EventTypeSelector } from "@/components/CreateEvent/EventTypeSelector";
import { OptionI } from "@/models/common";
import { Button } from "@/ui/Button/Button";
import { createEventApi } from "@/api/events";
import { useUserMe } from "@/store/auth";
import { getPrediction } from "@/api/prediction";
import { getMonthIdByStatus } from "@/feature/NewEventsTable/helper";

type Props = {
  modalOpen: boolean;
  setModalOpen: (v: boolean) => void;
  isLoading: boolean;
  setIsLoading: (v: boolean) => void;
};

export const addZero = (val: number) => {
  if (val > 9) return val;
  return `0${val}`;
};

export const CreateEvent = ({
  modalOpen,
  setModalOpen,
  isLoading,
  setIsLoading,
}: Props) => {
  const [type, setType] = useState<OptionI>();
  const [from, setFrom] = useState<Date | undefined>();
  const [to, setTo] = useState<Date | undefined>();
  const { userMe } = useUserMe();

  const onSave = () => {
    setIsLoading(true);
    const day = from.getDate();
    const start_time = `${addZero(from.getHours())}:${addZero(
      from.getMinutes()
    )}:${addZero(from.getSeconds())}`;

    const end_time = `${addZero(to.getHours())}:${addZero(
      to.getMinutes()
    )}:${addZero(to.getSeconds())}`;

    try {
      getPrediction(
        new URLSearchParams({
          month: String(from.getMonth() + 1),
          year: String(from.getFullYear()),
        })
      ).then((res) => {
        const mId = getMonthIdByStatus(res.results).id;
        createEventApi({
          kind: String(type.id),
          month: mId,
          day,
          start_time,
          end_time,
          user: userMe.id,
        });
      });
    } catch (e) {
      console.log(e);
    } finally {
      setModalOpen(false);
      setIsLoading(false);
    }
  };
  return (
    <CommonModal isOpen={modalOpen} close={() => setModalOpen(false)}>
      <div className={cls.form}>
        <div className={cls.field}>
          <EventTypeSelector setType={setType} />
        </div>
        <div className={cls.field}>
          <RangeTimePicker
            inline
            startDate={from}
            endDate={to}
            onChange={([d1, d2]) => {
              setFrom(d1);
              setTo(d2);
            }}
            hideFooter
          />
        </div>

        <Button onClick={() => onSave()} disabled={isLoading}>
          Создать
        </Button>
      </div>
    </CommonModal>
  );
};
